// pages/book/info/index.js
const $api = require("../../../api/book").API
const innerAudioContext = wx.createInnerAudioContext();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgurl:"https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1603365312,3218205429&fm=26&gp=0.jpg",
    currentValue: 0,
    books_type:"",
    isPlayAudio: false,
    audioSeek: 0,
    audioDuration: 0,
    showTime1: '00:00',
    showTime2: '00:00',
    audioTime: 0,
    audiolist: [],
    chapter_index:0,
    playmode:1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var t = this
    t.setData({
      
      books_type:options.books_type,
      chapter_index:options.chapter_index,
      audiolist:wx.getStorageSync('albumlist')
    })
    t.getBookVoiceChapterInfo()
  },
  onShow:function(){
    var t = this
    
  },
  onDrag(event) {
    this.setData({
      currentValue: event.detail.value,
    });
  },
  getBookVoiceChapterInfo(){
    var t = this,
    data = {
      bookChapterId:t.data.audiolist[t.data.chapter_index].books_voice_chapter_id,
      member_id:wx.getStorageSync('memberinfo').member_id
    }
    $api.getBookVoiceChapterInfo(data).then(res=>{
      t.setData({
        info:res.data,
        isPlayAudio:false,
        audioSeek:0,
        showTime1:"00:00"
      })
      //卸载页面，清除计步器
      clearInterval(t.data.durationIntval)
      t.Initialization();
      t.loadaudio();
    })
  },
  // 收藏书籍/章节
  insertBookOneCollection(){
    var t = this,
    data = {
      member_id:wx.getStorageSync('memberinfo').member_id,
      booksVoiceID:t.data.info.books_voice_id,
      booksVoiceChapterID:t.data.id,
      books_type:t.data.books_type,
    }
    $api.insertBookOneCollection(data).then(res=>{
      console.log(res)
      t.getBookVoiceChapterInfo()
    })
  },
  // 取消收藏书籍/章节
  cancelBookCollection(e){
    var t = this,
    index = e.currentTarget.dataset.index,
    data = {
      member_id:wx.getStorageSync('memberinfo').member_id,
      booksVoiceID:t.data.info.books_voice_id,
      booksVoiceChapterID:t.data.id,
    }
    $api.cancelBookCollection(data).then(res=>{
      console.log(res)
      t.getBookVoiceChapterInfo()
    })
  },
  //初始化播放器，获取duration
  Initialization() {
    var t = this;
    console.log("Initialization")
    if (t.data.audiolist[t.data.chapter_index].chapter_url.length != 0) {
      //设置src
      innerAudioContext.src = t.data.audiolist[t.data.chapter_index].chapter_url;
      //运行一次
      innerAudioContext.play();
      innerAudioContext.pause();
      innerAudioContext.onCanplay(() => {
        //初始化duration
        innerAudioContext.duration
        setTimeout(function () {
          //延时获取音频真正的duration
          var duration = innerAudioContext.duration;
          console.log(duration)
          var min = parseInt(duration / 60);
          var sec = parseInt(duration % 60);
          if (min.toString().length == 1) {
            min = `0${min}`;
          }
          if (sec.toString().length == 1) {
            sec = `0${sec}`;
          }
          t.setData({ audioDuration: duration, showTime2: `${min}:${sec}` });
        }, 1000)
      })
    }
  },
  //播放、暂停按钮
  playAudio() {
    //获取播放状态和当前播放时间
    var isPlayAudio = this.data.isPlayAudio;
    var seek = this.data.audioSeek;
    innerAudioContext.pause();
    //更改播放状态
    this.setData({ isPlayAudio: !isPlayAudio })
    if (isPlayAudio) {
      //如果在播放则记录播放的时间seek，暂停
      this.setData({ audioSeek: innerAudioContext.currentTime });
    } else {
      //如果在暂停，获取播放时间并继续播放
      innerAudioContext.src = this.data.audiolist[0].audiosrc;
      if (innerAudioContext.duration != 0) {
        this.setData({ audioDuration: innerAudioContext.duration });
      }
      //跳转到指定时间播放
      innerAudioContext.seek(seek);
      innerAudioContext.play();
    }
  },
  loadaudio() {
    var t = this;
    //设置一个计步器
    t.data.durationIntval = setInterval(function () { 
      //当歌曲在播放时执行
      if (t.data.isPlayAudio == true) {
        //获取歌曲的播放时间，进度百分比
        var seek = t.data.audioSeek;
        var duration = innerAudioContext.duration;
        var time = t.data.audioTime;
        time = parseInt(100 * seek / duration);
        //当歌曲在播放时，每隔一秒歌曲播放时间+1，并计算分钟数与秒数
        var min = parseInt((seek + 1) / 60);
        var sec = parseInt((seek + 1) % 60);
        //填充字符串，使3:1这种呈现出 03：01 的样式
        if (min.toString().length == 1) {
          min = `0${min}`;
        }
        if (sec.toString().length == 1) {
          sec = `0${sec}`;
        }
        var min1 = parseInt(duration / 60);
        var sec1 = parseInt(duration % 60);
        if (min1.toString().length == 1) {
          min1 = `0${min1}`;
        }
        if (sec1.toString().length == 1) {
          sec1 = `0${sec1}`;
        }
        //当进度条完成，停止播放，并重设播放时间和进度条
        if (time >= 100) {
          innerAudioContext.stop();
          t.setData({ audioSeek: 0, audioTime: 0, audioDuration: duration, isPlayAudio: false, showTime1: `00:00` });
          return false;
        }
        //正常播放，更改进度信息，更改播放时间信息
        t.setData({ audioSeek: seek + 1, audioTime: time, audioDuration: duration, showTime1: `${min}:${sec}`, showTime2: `${min1}:${sec1}` });
      }
    }, 1000);
  },
  //拖动进度条事件
  sliderChange(e) {
    var t = this;
    innerAudioContext.src = this.data.audiolist[0].audiosrc;
    //获取进度条百分比
    var value = e.detail;
    console.log(value)
    this.setData({ audioTime: value });
    var duration = this.data.audioDuration;
    //根据进度条百分比及歌曲总时间，计算拖动位置的时间
    value = parseInt(value * duration / 100);
    //更改状态
    this.setData({ audioSeek: value, isPlayAudio: true });
    //调用seek方法跳转歌曲时间
    innerAudioContext.seek(value);
    //播放歌曲
    innerAudioContext.play();
  },
  gotochapterlist(){
    var t = this
    wx.navigateTo({
      url: '/pages/book/chapterlist/index',
    })
  },
  // 上一曲
  previous(){
    var t = this
    var count = parseInt(t.data.chapter_index)
    if(t.data.playmode<3){
      if (count == 0){
        count = t.data.audiolist.length -1
      }else{
        count = count - 1
      }
      t.setData({
        chapter_index:count
      })
    }else{
      count = Math.floor((Math.random() * t.data.audiolist.length))
    }
    t.getBookVoiceChapterInfo();
  },
  // 下一曲
  next(){
    var t = this
    var count = parseInt(t.data.chapter_index)
    if(t.data.playmode<3){
      if(count == t.data.audiolist.length-1){
        count = 0
      }else{
        count = count +1
      }
    }else{
      count = Math.floor((Math.random() * t.data.audiolist.length))
    }
    t.setData({
      chapter_index:count
    })
    t.getBookVoiceChapterInfo();
  },
  changemode(){
    var t = this
    var mode = t.data.playmode
    if(mode==3){
      mode=1
    }else{
      mode = mode + 1
    }
    t.setData({
      playmode:mode
    })
  }
})